//
//  Util.swift
//  guard
//
//  Created by linus on 2021/11/21.
//

import UIKit

public class Util: NSObject {
    private static let publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4xKeUgQ+Aoz7TLfAfs9+paePb5KIofVthEopwrXFkp8OCeocaTHt9ICjTT2QeJh6cZaDaArfZ873GPUn00eOIZ7Ae+TiA2BKHbCvloW3w5Lnqm70iSsUi5Fmu9/2+68GZRH9L7Mlh8cFksCicW2Y2W2uMGKl64GDcIq3au+aqJQIDAQAB"
    
    /// Encrypt with PKCS1v1.5.
    /// - parameter password: Message to encrypt
    /// - returns: Encrypted message
    ///
    /// Encrypt with PKCS1v1.5.
    ///
    public static func encryptPassword(_ password: String) -> String {
        let pubData: Data = Data(base64Encoded: publicKey)!
        
        let publicKeyPEM = SwKeyConvert.PublicKey.derToPKCS8PEM(pubData)
        
        let newPublicKeyPEM = self.fetchPEMString(oldPEMString: publicKeyPEM)
        
        let publicKeyDER = try? SwKeyConvert.PublicKey.pemToPKCS1DER(newPublicKeyPEM)
        
        let testData = password.data(using: String.Encoding.utf8)!
        
        let e = CC.RSA.encrypt(testData, derKey: publicKeyDER!, tag: Data(), padding: .pkcs1, digest: .none)
        
        return e.base64EncodedString()
    }
    
    /// 去掉公钥的回车换行符
    /// - Parameter oldPEMString: 包含回车换行符的PEM 字符串
    /// - Returns: 去掉公钥中回车换行符的PEM 字符串
    public static func fetchPEMString(oldPEMString:String ) ->String
    {
        let startIndex = oldPEMString.index(oldPEMString.firstIndex(of: "\n") ?? oldPEMString.endIndex, offsetBy: 3)
        let endIndex = oldPEMString.lastIndex(of: "\n") ?? oldPEMString.endIndex
        let newRange = startIndex..<endIndex
        
        return oldPEMString.replacingOccurrences(of: "\n", with: "", options: String.CompareOptions.caseInsensitive, range: newRange)
    }
}
